﻿@using System.Linq
@using MvcContrib.UI.Grid
@using XRM.Security.WebUI.Helpers
@using XRM.Security.WebUI.MvcHelpers
@using XRM.Security.DataAccess.Enums
@model XRM.Security.WebUI.Models.Request.RequestWorkKindModel
@{
    Layout = null;
}

@{
    int[] simpleTextCode = { (int)WorkKindParamCode.Comment, (int)WorkKindParamCode.Hostname, (int)WorkKindParamCode.CopyNumber, 
                                       (int)WorkKindParamCode.LastName, (int)WorkKindParamCode.FirstName, (int)WorkKindParamCode.MotherName, 
                                       (int)WorkKindParamCode.Post, (int)WorkKindParamCode.DeleteReason };
    int i = 0;
    string nameInput = "WorkKindList[" + Model.WorkKindIndex.ToString() + "].WorkKindParamList[{0}]";
    string nameModel = "WorkKindList" + Model.WorkKindIndex.ToString("000") + "_";
    string departmentId = Model.WorkKindContId + "_DepartmentId";
    string departmentAddressId = Model.WorkKindContId + "_DepartmentAddressId";
    const string inputCss = "form-control";
    const string divCss = "col-sm-8";
}

@if (!Model.WorkKind.IsFixed)
{
    <p style="color:red;">Данный вид работ не вносит изменения в карточку пользователя</p>
}

@{
    
    bool statusDocDisable = false;
    if (Model.WorkKind.CustomId == (int)WorkKindCode.CertCreate)
    {
        var certParam = Model.WorkKindParamList.Where(x => x.WorkKindParam.CustomId == (int)WorkKindParamCode.Cert).SingleOrDefault();
        if ((certParam != null) && (certParam.RequestCertId.HasValue) && (certParam.RequestCertId.Value > 0))
        {
            statusDocDisable = true;
        }
    }
}

@foreach (XRM.Security.WebUI.Models.Request.RequestWorkKindParamModel item in Model.WorkKindParamList)
{
    @Html.Hidden(string.Format(nameInput, i.ToString()) + ".WorkKindParamId", item.WorkKindParamId)
    @Html.Hidden(string.Format(nameInput, i.ToString()) + ".Id", item.Id)

    if (simpleTextCode.Contains(item.WorkKindParam.CustomId))
    {
        <div class="form-group">
            @Html.Label(item.WorkKindParam.Name, new { @class = "control-label" })
            <div class="@divCss">
                @Html.TextBox(string.Format(nameInput, i.ToString()) + ".ParamValue", item.ParamValue, new { @class = "form-control" })
            </div>
        </div>
    }
    else if (item.WorkKindParam.CustomId == (int)WorkKindParamCode.Department)
    {
        <div class="form-group">
            @Html.Label("Структурное подразделение", new { @class = "control-label" })
            
            <div class="@divCss">
                @if (Model.ReadOnly)
                {
                    @Html.DropDownList(string.Format(nameInput, i.ToString()) + ".DepartmentId", new SelectList(Model.DepartmentAllList, "Id", "Name", item.DepartmentId),
                    new { @class = "form-control", id = departmentId })
                }
                else
                {
                    @Html.DropDownList(string.Format(nameInput, i.ToString()) + ".DepartmentId", new SelectList(Model.DepartmentNotDeletedList, "Id", "Name", item.DepartmentId),
                    new { @class = "form-control", id = departmentId })
                }
            </div>
        </div>
        <div class="form-group">
            @Html.Label("Адрес", new { @class = "control-label" })
            <div class="@divCss">
                @Html.DropDownList(string.Format(nameInput, i.ToString()) + ".DepartmentAddressId", new SelectList(Model.DepartmentAllList, "Id", "Name"),
                    new { @class = "form-control", id = departmentAddressId })
            </div>
        </div>
    
        <script type="text/javascript">
            $('#@(departmentId)').change(function () {
                GetDepartmentAddressEx(this.value, $('#@(departmentAddressId)'));
            });
            $('#@(departmentAddressId)').prop('disabled', true);
            $('#@(departmentId)').trigger("change");

            @if (item.DepartmentAddressId > 0)
            {
                <text>$('#@(departmentAddressId)').val('@(item.DepartmentAddressId.ToString())')</text>
            }

        </script>
    }
    else if (item.WorkKindParam.CustomId == (int)WorkKindParamCode.SkziKind)
    {
        <div class="form-group">
            @Html.Label(item.WorkKindParam.Name, new { @class = "control-label" })
            <div class="@divCss">
                @if (Model.ReadOnly)
                {
                    @Html.DropDownList(string.Format(nameInput, i.ToString()) + ".SkziKindId", new SelectList(Model.SkziKindAllList, "Id", "ShortName", item.SkziKindId ?? -1), new { @class = "form-control" })
                }
                else
                {
                    @Html.DropDownList(string.Format(nameInput, i.ToString()) + ".SkziKindId", new SelectList(Model.SkziKindNotDeletedList, "Id", "ShortName", item.SkziKindId ?? -1), new { @class = "form-control" })
                }
            </div>
        </div>
    }
    else if (item.WorkKindParam.CustomId == (int)WorkKindParamCode.StatusDoc)
    {
        if (!statusDocDisable)
        {
        <div class="form-group">
            @Html.Label(item.WorkKindParam.Name, new { @class = "control-label" })
            <div class="@divCss">
                @Html.DropDownList(string.Format(nameInput, i.ToString()) + ".ParamValue", new SelectList(Model.StatusDocList, "Value", "Text", item.ParamValue), new { @class = "form-control" })
            </div>
        </div>
        }
        else
        {
        <div class="form-group">
            @Html.Hidden(string.Format(nameInput, i.ToString()) + ".ParamValue", item.ParamValue)
            @Html.Label(item.WorkKindParam.Name, new { @class = "control-label" })
            <div class="@divCss">
                @Html.DropDownList(string.Format(nameInput, i.ToString()) + ".DisabledParamValue", new SelectList(Model.StatusDocList, "Value", "Text", item.ParamValue), new { @class = "form-control", disabled = "disabled" })
            </div>
        </div>
        }
    }
    else if (item.WorkKindParam.CustomId == (int)WorkKindParamCode.SerialNumberAdd)
    {
        <div class="form-group">
                @Html.Label("Серийный номер", new { @class = "control-label" })
                <div class="@divCss">
                    @Html.TextBox(string.Format(nameInput, i.ToString()) + ".ParamValue", item.ParamValue, new { @class = "form-control" })
                </div>
        </div>
        <div class="form-group">
                @Html.Label("Hostname", new { @class = "control-label" })
                <div class="@divCss">
                    @Html.TextBox(string.Format(nameInput, i.ToString()) + ".ParamValue1", item.ParamValue1, new { @class = "form-control" })
                </div>
        </div>
    }
    else if (item.WorkKindParam.CustomId == (int)WorkKindParamCode.SerialNumberExists)
    {
        <div class="form-group">
            @Html.Label(item.WorkKindParam.Name, new { @class = "control-label" })
            <div class="@divCss">
                @Html.DropDownList(string.Format(nameInput, i.ToString()) + ".PCId", new SelectList(Model.PCUserList, "Id", "SerialNumber", item.PCId ?? -1), new { @class = "form-control" })
            </div>
        </div>
    }
    else if (item.WorkKindParam.CustomId == (int)WorkKindParamCode.InfoSystem)
    {
        <div class="form-group">
            @Html.Label(item.WorkKindParam.Name, new { @class = "control-label" })
            <div class="@divCss">
                @if (Model.CloseDate.HasValue)
                {
                    @Html.DropDownList(string.Format(nameInput, i.ToString()) + ".InfoSystemId", new SelectList(Model.InfoSystemUserList, "Id", "InfoSystemName", item.InfoSystemId ?? -1), new { @class = "form-control" })
                }
                else
                {
                    @Html.DropDownList(string.Format(nameInput, i.ToString()) + ".InfoSystemId", new SelectList(Model.InfoSystemUserList.Where(x => x.InMaintenance).OrderBy(x => x.InfoSystemName).ToList(), "Id", "InfoSystemName", item.InfoSystemId ?? -1), new { @class = "form-control" })
                }
            </div>
        </div>
    }
    else if (item.WorkKindParam.CustomId == (int)WorkKindParamCode.StickerNumber)
    {
        <div class="form-group">
            @Html.Label(item.WorkKindParam.Name, new { @class = "control-label" })
            <div class="@divCss" id="@(nameModel)stickerArray">
                <div data-bind="template: { name: 'sticker-template', foreach: Sticker }"></div>
                @if (!Model.ReadOnly)
                {
                    <a href="#" style="padding-bottom: 20px" data-bind="click: addSticker">Добавить номер наклейки</a>
                }
            </div>
        </div>
    
        <script type="text/html" id="sticker-template">
        <div class="input-list-item" data-bind="css: { 'input-group': $index() >= 0 }">
            <input type="text" class="form-control" maxlength="100" data-bind="attr: { name: baseName + '.WorkKindParamSpecList[' + $index() + '].ParamValue' }, value: name" />
            <span class="input-group-btn" data-bind="visible: $index() >= 0">
                <button title="Удалить номер наклейки" class="btn btn-default" type="button" data-bind="click: $parent.removeSticker">
                    <i class="fa fa-times"></i>
                </button>
            </span>
        </div>
        </script>
    
        <script type="text/javascript">
        function @(nameModel)StickerParamViewModel() {
            var self = this;

            self.Sticker = ko.observableArray([
                @{
                if ((item.WorkKindParamSpecList != null) && (item.WorkKindParamSpecList.Count() > 0))
                {
                    foreach (var itemSpec in item.WorkKindParamSpecList)
                    {
                        <text>{ id: '@itemSpec.Id', name: '@Html.Raw(Utils.PrepareStringToJS(itemSpec.ParamValue))', baseName: '@string.Format(nameInput, i.ToString())' },</text>
                    }
                }
                }
            ]);

            self.addSticker = function () {
                self.Sticker.push({ id: "-1", name: "", baseName: '@string.Format(nameInput, i.ToString())' });
            };

            self.removeSticker = function () {
                self.Sticker.remove(this);
            };
        }

            ko.applyBindings(new @(nameModel)StickerParamViewModel(), document.getElementById("@(nameModel)stickerArray"));
        </script>
    }
    else if (item.WorkKindParam.CustomId == (int)WorkKindParamCode.Cert)
    {
        @Html.Hidden(string.Format(nameInput, i.ToString()) + ".RequestCertId", item.RequestCertId, new { id = nameModel + "RequestCertId" })
        @Html.Hidden(string.Format(nameInput, i.ToString()) + ".DataId", item.DataId, new { id = nameModel + "DataId" })
        <input type="hidden" id="@(nameModel)UploadResult" />
    
        <div id="@(nameModel)cert">
        @if (item.RequestCertId.HasValue)
        {
            @Html.Partial("CertTable", item.Cert, new ViewDataDictionary { { "BaseName", nameModel }, { "ReadOnly", Model.ReadOnly }, { "WorkKindIndex", Model.WorkKindIndex }, { "RequestWorkKindParamId", item.Id } })
        }
        else if (!Model.ReadOnly)
        {
            @Html.Partial("_FileUploaderPartialArray", new XRM.Security.WebUI.Models.FileUploaderModel() { BaseName = nameModel, IsOneFile = true, UploadUrl = @Url.Action("Upload", "CertRegister") })
            <p id="@(nameModel)UploadErrorMessage" class="error-message"></p>
        }
        </div>
        
       <script type="text/javascript">
           function @(nameModel)GetSelectedCert() {
               $.ajax({
                   async: false,
                   cache: false,
                   type: 'POST',
                   url: '@(Url.Action("GetSelectedCert", "Request"))',
                   success: function (result) {
                       $('#@(nameModel + "RequestCertId")').val(result);
                       $('#@(nameModel)cert').load('@(Url.Action("CertTable", "Request"))' + '?id=' + result + '&baseName=@(nameModel)', function () { });
                   },
                   error: handleAjaxError
               });
            }
       </script>
    }

    ++i;
}    

@if ((Model.ReadOnly) && (Model.CloseDate.HasValue))
{
        <div class="form-group">
            @Html.LabelFor(m => m.CloseDate, new { @class = "control-label" })
            <div class="@divCss">
                @Html.EditorFor(m => m.CloseDate, new ViewDataDictionary { { "disabled", "disabled" } })
            </div>
        </div>
}
else if ((!Model.ReadOnly) && (Model.RequestId > 0))
{
        <input class="btn btn-primary" id="CloseWork" type="button" value="Закрыть работу" onclick="SubmitForm('closeWorkKind', '@(Model.Id.Value.ToString())')">
    
        @Html.DialogFormButton(new DialogButtonOptions()
   {
       Text = "Закрыть работу",
       ContentUrl = Url.Action("CloseDialog", "Request", new { requestWorkKindId = Model.Id }),
       Width = "400",
       Id = "dlgCloseRequestWorkKindDialog",
       ButtonCss = "btn btn-primary hidden",
       OnSuccess = "RefreshPage",
       ButtonId = "CloseWorkKind" + Model.Id.Value.ToString()
   })
}
@if (!Model.ReadOnly)
{
    <hr/>
}
<script type="text/javascript">
    $(document).ready(function () {
        BindDialogButtons();
        @if (Model.ReadOnly)
        {
                <text>
                    var divId = 'divWorkKind' + '@(Model.WorkKindIndex.ToString())' + '_sub';
                    ReadOnlyDiv(divId);
                </text>
            }
    });
</script>
